using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

using ZeroconfService;

namespace PublishServiceSample
{
	public partial class Publish : Form
	{
		bool mPublishing = false;
		NetService publishService = null;

		public Publish()
		{
			InitializeComponent();
		}

		private void DoPublish()
		{
			try
			{
				publishService = new NetService("", serviceTypeTextBox.Text,
					serviceNameTextBox.Text, Int32.Parse(portTextBox.Text));

				/* HARDCODE TXT RECORD */
				System.Collections.Hashtable dict = new System.Collections.Hashtable();
				byte[] byte1 = Encoding.UTF8.GetBytes("This is some value");
				byte[] byte2 = Encoding.UTF8.GetBytes("And another value...");
				dict.Add("First TXT Key", byte1);
				dict.Add("Some Data", byte2);
				publishService.TXTRecordData = NetService.DataFromTXTRecordDictionary(dict);

				publishService.Publish();
			}
			catch (DNSServiceException e)
			{
				MessageBox.Show(String.Format("A DNSServiceException occured: {0}", e.Message), "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
				return;
			}
			catch (Exception e)
			{
				MessageBox.Show(String.Format("An exception occured: {0}", e.Message), "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
				return;
			}
			serviceNameTextBox.Enabled = false;
			serviceTypeTextBox.Enabled = false;
			portTextBox.Enabled = false;

			startStopButton.Text = "Stop";

			mPublishing = true;
		}

		private void StopPublish()
		{
			if (publishService != null)
			{
				publishService.Stop();
			}

			serviceNameTextBox.Enabled = true;
			serviceTypeTextBox.Enabled = true;
			portTextBox.Enabled = true;

			startStopButton.Text = "Stop";

			mPublishing = false;
		}

		private void startStopButton_Click(object sender, EventArgs e)
		{
			if (!mPublishing)
				DoPublish();
			else
				StopPublish();
		}

		private void Publish_Resize(object sender, EventArgs e)
		{
			if (FormWindowState.Minimized == WindowState)
				Hide();
		}

		private void notifyIcon1_DoubleClick(object sender, EventArgs e)
		{
			Show();
			WindowState = FormWindowState.Normal;
		}
	}
}